package com.kt.sso.test.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Desc:
 *
 * @author: keen
 * Date: 2020-06-21
 * Time: 15:09
 */
@Service
public class AuthService {
    private final static String GRANT_TYPE = "password";
    private final static String CLIENT_ID = "XcWebApp";
    private final static String CLIENT_SECRET = "XcWebApp";
    private final static String TOKEN_URL = "http://127.0.0.1:8060/sso/server/oauth/token";

    @Autowired
    private RestTemplate restTemplate;

    public Map<String, Object> getToken(String username, String password) {
        //请求Head
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        headers.add("Authorization", getHttpBasic());
        //请求Body
        MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
        body.add("grant_type", GRANT_TYPE);
        body.add("username", username);
        body.add("password", password);
        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(body, headers);
        ResponseEntity<Map> responseEntity = restTemplate.exchange(TOKEN_URL, HttpMethod.POST, httpEntity, Map.class);
        if (responseEntity.getStatusCode().is4xxClientError()) {
            throw new RuntimeException("");
        }
        return responseEntity.getBody();
    }

    private String getHttpBasic() {
        String basic = CLIENT_ID + ":" + CLIENT_SECRET;
        return "Basic " + Base64.getEncoder().encodeToString(basic.getBytes(StandardCharsets.UTF_8));
    }
}
